package com.rc.evcharger.protocol.ylevcharger.netty.listener;

import com.rc.evcharger.protocol.ylevcharger.netty.server.YLNettyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * netty监听器,需要在web.xml加载启动
 */
public class YlNettyListener implements ServletContextListener {
    Logger logger = LoggerFactory.getLogger(YlNettyListener.class);
    private static WebApplicationContext springContext;

    /**
     * 在listener里启动netty服务,不能再主线程里面启动，在主线程启动会阻塞 tomcat的启动，需要new 一个线程里面启动
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.warn("YlnettyListener Startup!");
        new Thread() {
            @Override
            public void run() {
                try {
                    new YLNettyServer(9009).run();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
        System.out.println("afe");
    }

    public static ApplicationContext getApplicationContext() {
        return springContext;
    }

    /**
     * 关闭服务时将所有桩设成离线
     * 并且将挂起的订单进行保存到redis中
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //将所有桩的登录状态设为离线
        logger.info("销毁进程，关闭服务");
        //ElecPileService elecPileService = (ElecPileService) springContext.getBean("elecPileService");
        //elecPileService.updatePileOffLine();
        //redisService.putExOrder();
    }
}
